package com.qcby.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qcby.common.exception.BusinessException;
import com.qcby.common.utils.JwtUtil;
import com.qcby.common.utils.SecurityUtils;
import com.qcby.entity.TUser;
import com.qcby.form.LoginForm;
import com.qcby.form.RegisterForm;
import com.qcby.form.UpdatePasswordForm;
import com.qcby.form.UserUpdateForm;
import com.qcby.mapper.TUserMapper;
import com.qcby.mapper.TUserRoleMapper;
import com.qcby.service.TUserService;
import com.qcby.vo.LoginVO;
import com.qcby.vo.UserInfoVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2025-02-04
 */
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements TUserService {

    @Autowired
    private TUserMapper userMapper;

    @Autowired
    private TUserRoleMapper userRoleMapper;

    @Override
    @Transactional
    public void register(RegisterForm form) {
        // 验证用户名是否已存在
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", form.getUsername());
        if (userMapper.selectCount(queryWrapper) > 0) {
            throw new BusinessException("用户名已存在");
        }

        // 创建用户
        TUser user = new TUser();
        BeanUtils.copyProperties(form, user);
        // 密码加密
        user.setPassword(DigestUtils.md5DigestAsHex(form.getPassword().getBytes()));
        user.setVersion(LocalDateTime.now());
        user.setIsDeleted(0);
        
        userMapper.insert(user);

        // 分配默认角色
        userRoleMapper.insertDefaultRole(user.getUserId());
    }

    @Override
    public LoginVO login(LoginForm form) {
        // 查询用户
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", form.getUsername())
                .eq("password", DigestUtils.md5DigestAsHex(form.getPassword().getBytes()))
                .eq("is_deleted", 0);

        TUser user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new BusinessException("用户名或密码错误");
        }

        // 生成token
        String token = JwtUtil.generateToken(user.getUserId());

        // 构建登录返回信息
        LoginVO loginVO = new LoginVO();
        loginVO.setToken(token);
        loginVO.setUserInfo(convertToUserInfoVO(user));

        return loginVO;
    }

    @Override
    public UserInfoVO getCurrentUserInfo() {
        Integer userId = SecurityUtils.getCurrentUserId();
        TUser user = userMapper.selectById(userId);
        return convertToUserInfoVO(user);
    }

    @Override
    public void updateUserInfo(UserUpdateForm form) {
        Integer userId = SecurityUtils.getCurrentUserId();
        TUser user = new TUser();
        BeanUtils.copyProperties(form, user);
        user.setUserId(userId);
        user.setVersion(LocalDateTime.now());
        userMapper.updateById(user);
    }

    @Override
    public void updatePassword(UpdatePasswordForm form) {
        Integer userId = SecurityUtils.getCurrentUserId();
        TUser user = userMapper.selectById(userId);

        // 验证原密码
        if (!user.getPassword().equals(DigestUtils.md5DigestAsHex(form.getOldPassword().getBytes()))) {
            throw new BusinessException("原密码错误");
        }

        // 更新密码
        user.setPassword(DigestUtils.md5DigestAsHex(form.getNewPassword().getBytes()));
        user.setVersion(LocalDateTime.now());
        userMapper.updateById(user);
    }

    private UserInfoVO convertToUserInfoVO(TUser user) {
        if (user == null) {
            return null;
        }
        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtils.copyProperties(user, userInfoVO);
        return userInfoVO;
    }
}
